using Microsoft.AspNetCore.Mvc;
using Product.Service;
using hao_Dto;
using hao_Common.Response.Extensions;
using Microsoft.AspNetCore.Authorization;

namespace hao_Product.Api.Controllers
{
    /// <summary>
    /// 内部服务调用控制器
    /// 专门用于微服务间的内部通信，不需要用户认证
    /// </summary>
    [ApiController]
    [Route("api/internal/product")]
    public class InternalController : ControllerBase
    {
        private readonly IProductService _productService;
        private readonly ILogger<InternalController> _logger;

        public InternalController(
            IProductService productService,
            ILogger<InternalController> logger)
        {
            _productService = productService;
            _logger = logger;
        }

        /// <summary>
        /// 获取商品详情（内部服务调用）
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <returns>商品详情</returns>
        /// <response code="200">获取成功</response>
        /// <response code="404">商品不存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("{id}")]
        [ProducesResponseType(typeof(ProductResponseDto), 200)]
        [ProducesResponseType(404)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetProductInternal(Guid id)
        {
            try
            {
                var product = await _productService.GetProductByIdAsync(id);
                return product == null 
                    ? this.NotFoundResult("商品不存在") 
                    : this.SuccessResult(product, "获取商品详情成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "内部服务获取商品详情失败，ID: {ProductId}", id);
                return this.ServerErrorResult("获取商品详情失败");
            }
        }

        /// <summary>
        /// 批量获取商品详情（内部服务调用）
        /// </summary>
        /// <param name="ids">商品ID列表</param>
        /// <returns>商品详情列表</returns>
        /// <response code="200">获取成功</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("batch")]
        [ProducesResponseType(typeof(List<ProductResponseDto>), 200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> GetProductsBatch([FromBody] List<Guid> ids)
        {
            try
            {
                var products = new List<ProductResponseDto>();
                foreach (var id in ids)
                {
                    var product = await _productService.GetProductByIdAsync(id);
                    if (product != null)
                    {
                        products.Add(product);
                    }
                }
                return this.SuccessResult(products, "批量获取商品详情成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "内部服务批量获取商品详情失败，IDs: {ProductIds}", string.Join(",", ids));
                return this.ServerErrorResult("批量获取商品详情失败");
            }
        }

        /// <summary>
        /// 验证商品是否存在且可用（内部服务调用）
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <returns>验证结果</returns>
        /// <response code="200">验证成功</response>
        /// <response code="404">商品不存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpGet("{id}/validate")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(404)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> ValidateProduct(Guid id)
        {
            try
            {
                var product = await _productService.GetProductByIdAsync(id);
                if (product == null)
                {
                    return this.NotFoundResult("商品不存在或已下架");
                }

                return this.SuccessResult(new 
                { 
                    id = product.Id,
                    title = product.Title,
                    price = product.Price,
                    userId = product.UserId,
                    isAvailable = true
                }, "商品验证成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "内部服务验证商品失败，ID: {ProductId}", id);
                return this.ServerErrorResult("验证商品失败");
            }
        }

        /// <summary>
        /// 健康检查（内部服务）
        /// </summary>
        /// <returns>服务状态</returns>
        [HttpGet("health")]
        public IActionResult Health()
        {
            return this.SuccessResult(new { status = "healthy", service = "product-internal", timestamp = DateTime.UtcNow });
        }
    }
}